<?php
/**
 * Created by JetBrains PhpStorm.
 * User: vander
 * Date: 5/11/13
 * Time: 2:55 PM
 * To change this template use File | Settings | File Templates.
 */
$data = $_POST['data'];
$fileName = $_POST['fileName'];
$bookPath = "Server/".$fileName;
//tao folder voi id trong Server
if(!file_exists($bookPath)){
    mkdir($bookPath);
}

//Ghi file mo ta len server
$filePath = $bookPath . "/" . $fileName . ".json";
$handle = fopen($filePath, 'w+');
fwrite($handle,$data);
fclose($handle);

//khoi tao resources folder
if(!file_exists($bookPath . "/" . "resources")){
    mkdir($bookPath. "/" . "resources");
}
$resourcesPath = $bookPath . "/" . "resources";

$resArray = glob("MyUploader/server/php/files/"."*.*");
$resArrayLength = count($resArray);
for($i = 0; $i<$resArrayLength; $i++){
    $des = str_replace("MyUploader/server/php/files", $resourcesPath, $resArray[$i]);
    copy($resArray[$i], $des);
}

///Doc collections.json
$collectionFile = "Server/collections.json";
$handle = fopen($collectionFile, "r");
$collectionStr = "";
while(!feof($handle)){
    $collectionStr = $collectionStr . fgets($handle);
}
$collection = json_decode($collectionStr);
fclose($handle);

//Khoi tao thong tin moi vao book
$newBookInfo = new stdClass();
$newBookInfo->bookId = $fileName;
$newBookInfo->resourcesPath = $fileName."/resources/";
$newBookInfo->name = $_POST['bookName'];
$newBookInfo->coverImage = $_POST['coverImage'];
$newBookInfo->visible= "true";

//Kiem tra xem trong collection hien tai co book do chua, neu co thi chi can cap nhat lai thong tin
$existedInCollection = false;
for($i = 0; $i<count($collection->books); $i++){
    if($newBookInfo->bookId == $collection->books[$i]->bookId){
        $collection->books[$i] = $newBookInfo;
        $existedInCollection = true;
        break;
    }
}
//Append thong tin book moi vao collection neu khong ton tai
if(!$existedInCollection){
    array_push($collection->books, $newBookInfo);
}


//Luu lai
$collectionFile = "Server/collections.json";
$handle = fopen($collectionFile, "w+");
$collectionStr = json_encode($collection);
fwrite($handle, $collectionStr);
fclose($handle);

echo json_encode( array("exportedPath"=>$filePath, "fileName"=>$fileName.".json"));
?>